{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6cea1194-0ca6-41ea-8aca-ac8e6f4e6678",
   "metadata": {},
   "source": [
    "组合图表组件-Grid组件"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e759b93a-9957-4d4a-93bc-461526a2f200",
   "metadata": {},
   "source": [
    "该组件可以将不同的图标组合在一起"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f87ec62b-77fa-49b8-bf66-2eec67fe14fd",
   "metadata": {},
   "source": [
    "TimeLine组件"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78b30b6b-21c4-4223-92ae-1965efa77985",
   "metadata": {},
   "source": [
    "该组件可以根据时间的不同，生成对应时间的线段"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be1bb6b6-3bbb-43aa-8a8d-d00c74fb45ba",
   "metadata": {},
   "source": [
    "【1】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e05ace4-762e-436d-9b28-098db06a35ab",
   "metadata": {},
   "source": [
    "时序条形图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "a150d5bb-4ba2-4b0c-9791-1ae63e31a239",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\时序-单条line.html'"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyecharts.charts import Bar,Geo,Line,Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json','r',encoding='utf-8') as f:\n",
    "    data = json.loads(f.read()) # 由于是json数据，所有处理的时候要使用json.loads执行\n",
    "tb = pd.DataFrame(data,columns=['Income','Life Expectancy','Population','Country','Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland','France','Germany','Iceland','Norway','Poland','Russia','United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year','Income']].values.tolist()\n",
    "\n",
    "# 单条折线\n",
    "line = (\n",
    "    Line()\n",
    "    .add_xaxis([str(i) for i in years])\n",
    "    .add_yaxis('Russia',[i[1] for i in data_pair['Russia']],\n",
    "              is_symbol_show=False,\n",
    "              is_smooth=True,\n",
    "              label_opts=opts.LabelOpts(is_show=False))\n",
    ")\n",
    "line.render('时序-单条line.html') # 也是动态的"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49cbbbf3-4763-4544-ad1a-8394f042c0d5",
   "metadata": {},
   "source": [
    "【2】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5d47e2a-eb7b-4e06-bd2d-07bd54d59f3f",
   "metadata": {},
   "source": [
    "动态时序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "494d2a65-44e8-488d-8615-d7d008c49059",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\动态时序-单条line.html'"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyecharts.charts import Bar,Geo,Line,Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json','r',encoding='utf-8') as f:\n",
    "    data = json.loads(f.read()) # 由于是json数据，所有处理的时候要使用json.loads执行\n",
    "tb = pd.DataFrame(data,columns=['Income','Life Expectancy','Population','Country','Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland','France','Germany','Iceland','Norway','Poland','Russia','United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year','Income']].values.tolist()\n",
    "\n",
    "# 动态折线\n",
    "t1 = Timeline()\n",
    "\n",
    "for index,year in enumerate(years):  # !!!!!!!!!!!!   enumerate是什么意思\n",
    "    line = (\n",
    "    Line()\n",
    "    .add_xaxis([str(i) for i in years])\n",
    "    .add_yaxis('Russia',[i[1] for i in data_pair['Russia']][:index+1],\n",
    "              is_symbol_show=False,\n",
    "              is_smooth=True,\n",
    "              label_opts=opts.LabelOpts(is_show=False))\n",
    "    .set_global_opts(yaxis_opts=opts.AxisOpts(max_=70000))\n",
    "    )\n",
    "    t1.add(line,year)\n",
    "\n",
    "t1.add_schema(play_interval=400)\n",
    "t1.render('动态时序-单条line.html')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2887e3b3-d470-4f36-b6bd-5034c438650b",
   "metadata": {},
   "source": [
    "【3】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "022b5821-0d29-45e3-934b-e5a112ea10e1",
   "metadata": {},
   "source": [
    "时序-数据标记点绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "60847f6f-6ed8-4a9b-88a3-3914915bcd0a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\时序-数据标记点绘制.html'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyecharts.charts import Bar,Geo,Line,Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json','r',encoding='utf-8') as f:\n",
    "    data = json.loads(f.read()) # 由于是json数据，所有处理的时候要使用json.loads执行\n",
    "tb = pd.DataFrame(data,columns=['Income','Life Expectancy','Population','Country','Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland','France','Germany','Iceland','Norway','Poland','Russia','United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year','Income']].values.tolist()\n",
    "\n",
    "line = (\n",
    "    Line()\n",
    "    .add_xaxis([str(i) for i in years]) # 为动态折现添加x轴数据, 这里将YEARS列表中每个元素转换为字符串形式\n",
    ")\n",
    "# 创建MarkPointopts对象，用于配置标点\n",
    "# 标记点通常用于在图表中突出显示某些特定的数据点\n",
    "markerpoints = opts.MarkPointOpts(data=[opts.MarkPointItem(\n",
    "    name='Russia', # 标记点名称\n",
    "    coord=[str(years[-1]),data_pair['Russia'][-1][1]], # 标记点坐标, 这里使用年份列表的最后一个年份和Russia数据的最后一个值（所以-1）\n",
    "    value=data_pair['Russia'][-1][1],\n",
    "    symbol='image://https://static.toolonline.net/up/2023/1229/111823090.png', # 使用图片作为标记点的符号，这里设置的图片的URL\n",
    "    symbol_size=[45,30] # 标记点符号大小\n",
    ")],\n",
    "    label_opts=opts.LabelOpts(position='right',  # 标签的位置\n",
    "                             formatter=\"{b}:{c}\", # 标签的格式, {b}表示标记点的名称, {c}表示标记点的值\n",
    "                             font_weight='bold', # 标签的字体粗细\n",
    "                             color='auto')) # 标签的颜色, 这里设置为自动, 根据图表的主题颜色自动选择\n",
    "line.add_yaxis('Russia',\n",
    "              [i[1] for i in data_pair['Russia']],\n",
    "              is_symbol_show=False, # 是否显示数据点的符号, 这里设置为不显示\n",
    "              is_smooth=True,       # 是否平滑显示折现, 这里设置为是\n",
    "              label_opts=opts.LabelOpts(is_show=False),  # y轴数据的标签设置, 这里设置为不显示\n",
    "              markpoint_opts=markerpoints)   # 将前面配置的标记点应用到这个y轴数据上\n",
    "line.render('时序-数据标记点绘制.html')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd372411-b966-43cd-a498-fc4e2e1346f8",
   "metadata": {},
   "source": [
    "【4】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3718447c-58ea-4f10-9d76-1b09cb374813",
   "metadata": {},
   "source": [
    "动态时序-带标记折线图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "1ff2bf12-98b5-4cc1-bb4b-9a32bf40f48c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\动态时序-带标记折线图1.html'"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 时序-带标记折线图\n",
    "from pyecharts.charts import Bar, Geo, Line, Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json', 'r', encoding='utf-8') as f:\n",
    "    data = json.loads(f.read())   # 由于是json数据, 所以处理的时候要使用json.loads来进行\n",
    "\n",
    "tb = pd.DataFrame(data, columns=['Income', 'Life Expectancy', 'Population', 'Country', 'Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland', 'France', 'Germany', 'Iceland', 'Norway', 'Poland', 'Russia',\n",
    "    'United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year', 'Income']].values.tolist()\n",
    "\n",
    "# 时序-带标记折线图\n",
    "t1 = Timeline()\n",
    "# 对year列表进行枚举, 同时获取索引(index)和年份(year)\n",
    "for index, year in enumerate(years):\n",
    "    # 为当前年份创建一个标记点配置, 这里只针对'Russia'数据\n",
    "    markerpoints = opts.MarkPointOpts(data=[opts.MarkPointItem(\n",
    "        name='Russia', \n",
    "        coord=[str(year), data_pair['Russia'][index][1]],  # 坐标, x轴为年份, y轴为数据值\n",
    "        value=data_pair['Russia'][index][1],  # 标记点的值, 这里与y轴坐标相同\n",
    "        symbol_size=0,  # 标记点的大小设置为0, 即不显示标记点的图形\n",
    "    )\n",
    "                                           ],\n",
    "                                      label_opts=opts.LabelOpts(position='right',  # 标签位置的右侧\n",
    "                                                                formatter=\" {b}:{c}\", # 标签格式: {b}为系列名, {c}为数值\n",
    "                                                               font_weight='bold',  # 字体加粗\n",
    "                                                                 color='auto', # 颜色自动\n",
    "                                                               ),)\n",
    "    line = Line()  # 创建折线图对象\n",
    "    line.add_xaxis([str(i) for i in years]) # 为折线图添加x轴数据, 年份转换为字符串\n",
    "    # 为折线图添加y轴数据, 只添加到当前年份的数据, 使用切片 [:index+1]\n",
    "    line.add_yaxis('Russia', [i[1] for i in data_pair['Russia']][:index+1],\n",
    "                   is_symbol_show=False,  # 不显示数据点\n",
    "                   is_smooth=True,     # 折线平滑\n",
    "                   label_opts=opts.LabelOpts(is_show=False),  # 不显示标签\n",
    "                   markpoint_opts=markerpoints      # 设置标记点\n",
    "                  )\n",
    "    line.set_global_opts(yaxis_opts=opts.AxisOpts(max_=70000))  # 设置全局配置项, y轴最大值设置为70000\n",
    "    t1.add(line,year)  # 将折线图添加到时间线对象中, 以当前年份作为key\n",
    "t1.add_schema(play_interval=400)  # 为时间线对象设置播放间隔\n",
    "t1.render('动态时序-带标记折线图1.html') # 渲染到HTML中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "3ad289c1-f593-4b05-b2e9-526019cf9c33",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\动态时序-带标记折线图.html'"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 时序-带标记折线图\n",
    "from pyecharts.charts import Bar, Geo, Line, Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json', 'r', encoding='utf-8') as f:\n",
    "    data = json.loads(f.read())   # 由于是json数据, 所以处理的时候要使用json.loads来进行\n",
    "\n",
    "tb = pd.DataFrame(data, columns=['Income', 'Life Expectancy', 'Population', 'Country', 'Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland', 'France', 'Germany', 'Iceland', 'Norway', 'Poland', 'Russia',\n",
    "    'United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year', 'Income']].values.tolist()\n",
    "    # 时序-带标记折线图\n",
    "t1 = Timeline()\n",
    "# 对year列表进行枚举, 同时获取索引(index)和年份(year)\n",
    "for index, year in enumerate(years):\n",
    "    # 为当前年份创建一个标记点配置, 这里只针对'Russia'数据\n",
    "    markerpoints = opts.MarkPointOpts(data=[opts.MarkPointItem(\n",
    "        name='Russia', \n",
    "        coord=[str(year), data_pair['Russia'][index][1]],  # 坐标, x轴为年份, y轴为数据值\n",
    "        value=data_pair['Russia'][index][1],  # 标记点的值, 这里与y轴坐标相同\n",
    "        symbol='image://https://static.toolonline.net/up/2023/1229/111823090.png',\n",
    "        symbol_size=[45,30],  # 标记点的大小设置为0, 即不显示标记点的图形\n",
    "    )\n",
    "                                           ],\n",
    "                                      label_opts=opts.LabelOpts(position='right',  # 标签位置的右侧\n",
    "                                                                formatter=\" {b}:{c}\", # 标签格式: {b}为系列名, {c}为数值\n",
    "                                                               font_weight='bold',  # 字体加粗\n",
    "                                                                 color='auto', # 颜色自动\n",
    "                                                               ),)\n",
    "    line = (\n",
    "        Line()  # 创建折线图对象\n",
    "        .add_xaxis([str(i) for i in years]) # 为折线图添加x轴数据, 年份转换为字符串\n",
    "         # 为折线图添加y轴数据, 只添加到当前年份的数据, 使用切片 [:index+1]\n",
    "        .add_yaxis('Russia', [i[1] for i in data_pair['Russia']][:index+1],\n",
    "                   is_symbol_show=False,  # 不显示数据点\n",
    "                   is_smooth=True,     # 折线平滑\n",
    "                   label_opts=opts.LabelOpts(is_show=False),  # 不显示标签\n",
    "                   markpoint_opts=markerpoints      # 设置标记点\n",
    "                  )\n",
    "        .set_global_opts(yaxis_opts=opts.AxisOpts(max_=70000)))  # 设置全局配置项, y轴最大值设置为70000\n",
    "    t1.add(line,year)  # 将折线图添加到时间线对象中, 以当前年份作为key\n",
    "t1.add_schema(play_interval=400)  # 为时间线对象设置播放间隔\n",
    "t1.render('动态时序-带标记折线图.html') # 渲染到HTML中"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "937059d5-28e8-452c-84b6-e57bcb3408f4",
   "metadata": {},
   "source": [
    "【5】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bce8632b-7580-4338-9fdb-bd0d8f4b571b",
   "metadata": {},
   "source": [
    "动态时序-多条折线"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "4d55e3f2-e23e-4f06-8949-46a5c5b66fe3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\动态时序-多条折线.html'"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyecharts.charts import Bar,Geo,Line,Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json','r',encoding='utf-8') as f:\n",
    "    data = json.loads(f.read()) # 由于是json数据，所有处理的时候要使用json.loads执行\n",
    "tb = pd.DataFrame(data,columns=['Income','Life Expectancy','Population','Country','Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland','France','Germany','Iceland','Norway','Poland','Russia','United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year','Income']].values.tolist()\n",
    "\n",
    "pic_dict = {\n",
    "    'Russia': 'image://https://static.toolonline.net/up/2023/1229/111823090.png',\n",
    "    'Finland': 'image://https://static.toolonline.net/up/2023/1229/111822663.png',\n",
    "    'France': 'image://https://static.toolonline.net/up/2023/1229/111822034.png',\n",
    "    'Germany': 'image://https://static.toolonline.net/up/2023/1229/111821930.png',\n",
    "    'Iceland': 'image://https://static.toolonline.net/up/2023/1229/111821770.png',\n",
    "    'Norway': 'image://https://static.toolonline.net/up/2023/1229/111822880.png',\n",
    "    'Poland': 'image://https://static.toolonline.net/up/2023/1229/111821984.png',\n",
    "    'United Kingdom': 'image://https://static.toolonline.net/up/2023/1229/111822933.png'\n",
    "}\n",
    "\n",
    "# 自定义样式\n",
    "linestyle = {\n",
    "    'normal':{\n",
    "        'barBorderRadius':[20,20,20,20], # 柱子四个角圆角设计\n",
    "        'shadowColor':'rgba(108,80,243,0.9)', # 阴影的颜色\n",
    "        'shadowBlur':3, \n",
    "        'width':2\n",
    "    }\n",
    "}\n",
    "\n",
    "# 初始化timeline对象设置主题为浅色主题，宽度为100%,高度为窗口高度的100%\n",
    "t1 = Timeline(init_opts=opts.InitOpts(theme=ThemeType.LIGHT,width='100%',height='100vh'))\n",
    "\n",
    "# 定义函数，用于获取标记点配置\n",
    "def get_markerpoints(name,year,index,data_pair):\n",
    "    # 创建Markerpoint对象,包含一个标记点\n",
    "    markerpoints = opts.MarkPointOpts(data=[opts.MarkPointItem(\n",
    "        name=name, # 标记点名称\n",
    "        # 标记点坐标，年份为x轴, data_pair中对应的年份和指标的值为y轴\n",
    "        coord=[str(year),data_pair[name][index][1]],\n",
    "        # 标记点设置, 与y轴坐标相同\n",
    "        value=data_pair[name][index][1],\n",
    "        # 标记点符号，从pic_dict字典中获取\n",
    "        symbol=pic_dict[name],\n",
    "        # 标记点符号大小\n",
    "        symbol_size=[45, 30]\n",
    "    )],\n",
    "                                     label_opts=opts.LabelOpts(position='right',  # 标签位置的右侧\n",
    "                                                                formatter=\" {b}:{c}\", # 标签格式: {b}为系列名, {c}为数值\n",
    "                                                               font_weight='bold',  # 字体加粗\n",
    "                                                                 color='auto', # 颜色自动\n",
    "                                                               ))\n",
    "    return markerpoints\n",
    "\n",
    "# 遍历年份\n",
    "for index,year in enumerate(years):\n",
    "    line = Line()\n",
    "    line.add_xaxis([str(i) for i in years])\n",
    "    for item in countries: # 遍历国家或地区\n",
    "        line.add_yaxis(item,[i[1] for i in data_pair[item]][:index+1],\n",
    "                       is_symbol_show=False,  # 不显示数据点\n",
    "                       is_smooth=True,     # 折线平滑\n",
    "                       linestyle_opts=linestyle, # 线条样式配置\n",
    "                       label_opts=opts.LabelOpts(is_show=False),  # 不显示标签\n",
    "                       markpoint_opts=get_markerpoints(name=item,year=year,index=index,data_pair=data_pair)      # 设置标记点\n",
    "                      )\n",
    "        # 设置全局配置项\n",
    "        line.set_global_opts(yaxis_opts=opts.AxisOpts(max_=70000),\n",
    "                            tooltip_opts=opts.TooltipOpts(axis_pointer_type='line',trigger='axis')) # 提示框配置\n",
    "        t1.add(line,year) # 将折现添加到Timeline中, 以年份为key\n",
    "\n",
    "# 设置Timeline播放模式\n",
    "t1.add_schema(play_interval=400, # 播放速度\n",
    "             is_auto_play=False, # 关闭自动播放\n",
    "             is_loop_play=False) # 关闭循环播放\n",
    "# 动画配置效果\n",
    "# t1.options['animationDurationUpdate'] = 200  # 更新动画持续时间\n",
    "# t1.options['animationDuration'] = 10000  # 初始动画持续时间\n",
    "# t1.options['animation'] = 'auto' # 动画开启\n",
    "# # t1.options['animationDuationUpdate'] = 500  # 重复设置, 更新动画持续时间\n",
    "# t1.options['animationEasing'] = 'cubicInOut',  # 动画缓动效果\n",
    "# t1.options['animationEasingUpdate'] = 'cubicInOut',  # 动画更新时的缓动效果\n",
    "# t1.options['animationThreshold'] = 2000 # 动画触发阈值\n",
    "# t1.options['progressiveThreshold'] = 3000 # 渐进式渲染阈值\n",
    "# t1.options['progressive'] = 400  # 渐进式渲染模块大小\n",
    "# t1.options['hoverLayerThreshold'] = 3000  # 鼠标悬停时图层阈值\n",
    "t1.render('动态时序-多条折线.html')  #渲染 Timeline"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcf29e34-2671-41c3-aa92-5cff77f29854",
   "metadata": {},
   "source": [
    "【6】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b5162fd-7395-4965-809f-7d3067cd1228",
   "metadata": {},
   "source": [
    "动态时序-条形图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "f55360da-5ddd-4fab-b3c4-bdb460e9f335",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\jupyter\\\\动态时序-条形图.html'"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyecharts.charts import Bar,Geo,Line,Timeline\n",
    "from pyecharts.globals import JsCode\n",
    "from pyecharts import options as opts\n",
    "from pyecharts.globals import ThemeType\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "with open('./data/life-expectancy-table.json','r',encoding='utf-8') as f:\n",
    "    data = json.loads(f.read()) # 由于是json数据，所有处理的时候要使用json.loads执行\n",
    "tb = pd.DataFrame(data,columns=['Income','Life Expectancy','Population','Country','Year'])\n",
    "tb.drop(0,inplace=True)\n",
    "tb = tb[tb['Year'] >= 1950]\n",
    "countries = [\n",
    "    'Finland','France','Germany','Iceland','Norway','Poland','Russia','United Kingdom'\n",
    "]\n",
    "years = tb['Year'].unique().tolist()\n",
    "data_pair = {}\n",
    "for i in countries:\n",
    "    data_pair[i] = tb.loc[tb['Country'] == i].sort_values(by='Year')[['Year','Income']].values.tolist()\n",
    "\n",
    "# 自定义样式\n",
    "baritemstyle = {\n",
    "    'normal':{\n",
    "        'borderWidth':1,\n",
    "        'color':JsCode(\n",
    "            \"\"\"new echarts.graphic.LinearGradient(0,0,1,1,[\n",
    "            { offset: 1,color: 'rgb(255,191,0)'},\n",
    "            { offset: 0,color: 'rgb(224,62,76)'}\n",
    "            ])\"\"\"\n",
    "        ),\n",
    "        'shadowColor':'green',\n",
    "        'shadowBlur':1,\n",
    "        'barBorderRadius':[10,10,10,10]\n",
    "    }\n",
    "}\n",
    "\n",
    "tb1 = tb.copy()\n",
    "tb1.sort_values(by=['Year','Income'],inplace=True)\n",
    "data_bar = {}\n",
    "for index,year in enumerate(years):\n",
    "    data_bar[year] = tb1[tb1['Year'] == year][['Country','Income']].values.tolist()\n",
    "\n",
    "t2 = Timeline()\n",
    "for index,year in enumerate(years):\n",
    "    bar = (\n",
    "        Bar()\n",
    "        .add_xaxis([i[0] for i in data_bar[year][-8:]])\n",
    "        .add_yaxis('',[i[1] for i in data_bar[year]][-8:],\n",
    "                  label_opts=opts.LabelOpts(position='insideLeft',\n",
    "                                            color='black',\n",
    "                                           formatter=\"{b}:{c}\",\n",
    "                                           font_weight='bold',\n",
    "                                           font_size=14),\n",
    "                  itemstyle_opts=baritemstyle)\n",
    "        .set_global_opts(\n",
    "            title_opts=opts.TitleOpts(title='top 8',pos_left='10%',pos_top='5%',\n",
    "                                     title_textstyle_opts=opts.TextStyleOpts(font_weight='bold',font_size=16)),\n",
    "            xaxis_opts=opts.AxisOpts(is_show=False,max_=65000),\n",
    "            yaxis_opts=opts.AxisOpts(is_show=False)\n",
    "        )\n",
    "        .reversal_axis() # 转置成水平条形\n",
    "    )\n",
    "    t2.add(bar,year)\n",
    "\n",
    "t2.add_schema(play_interval=400)\n",
    "t2.render('动态时序-条形图.html')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15cc4593-4eee-4745-ad73-79daccc851b1",
   "metadata": {},
   "source": [
    "【7】"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c11ea43-7a7a-46c8-a725-e89ae9a776a5",
   "metadata": {},
   "source": [
    "动态时序-地图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "63d5a7e2-9718-45ba-90f9-d8fb65ddeeb3",
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: './data/crood_text.json'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[63], line 4\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mpyecharts\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mglobals\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m ThemeType,ChartType,SymbolType\n\u001b[0;32m      2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mpyecharts\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mcommons\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mutils\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m JsCode\n\u001b[1;32m----> 4\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m./data/crood_text.json\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mr\u001b[39m\u001b[38;5;124m'\u001b[39m,encoding\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mutf-8\u001b[39m\u001b[38;5;124m'\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m f:\n\u001b[0;32m      5\u001b[0m     data_loc \u001b[38;5;241m=\u001b[39m \u001b[38;5;28meval\u001b[39m(f\u001b[38;5;241m.\u001b[39mread())\n\u001b[0;32m      7\u001b[0m jsondict \u001b[38;5;241m=\u001b[39m {i:data_loc[i] \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m countries}\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\IPython\\core\\interactiveshell.py:324\u001b[0m, in \u001b[0;36m_modified_open\u001b[1;34m(file, *args, **kwargs)\u001b[0m\n\u001b[0;32m    317\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m file \u001b[38;5;129;01min\u001b[39;00m {\u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m}:\n\u001b[0;32m    318\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m    319\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIPython won\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt let you open fd=\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfile\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m by default \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    320\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mas it is likely to crash IPython. If you know what you are doing, \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    321\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124myou can use builtins\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m open.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    322\u001b[0m     )\n\u001b[1;32m--> 324\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m io_open(file, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: './data/crood_text.json'"
     ]
    }
   ],
   "source": [
    "from pyecharts.globals import ThemeType,ChartType,SymbolType\n",
    "from pyecharts.commons.utils import JsCode\n",
    "\n",
    "with open('./data/crood_text.json','r',encoding='utf-8') as f:\n",
    "    data_loc = eval(f.read())\n",
    "\n",
    "jsondict = {i:data_loc[i] for i in countries}\n",
    "with open('./data/crood_text.json','w',encoding='utf-8') as f:\n",
    "    f.write(json.dumps(data_loc))\n",
    "\n",
    "itemstyle_geo = {\n",
    "    'normal':{\n",
    "        'borderWidth':1,\n",
    "        'color':JsCode(\n",
    "            \"\"\"new echarts.graphic.LinearGradient(0,0,1,1,[\n",
    "            { offset: 1,color: 'rgb(255,191,0)'},\n",
    "            { offset: 0,color: 'rgb(224,62,76)'}\n",
    "            ])\"\"\"\n",
    "        ),\n",
    "        'shadowColor':'green',\n",
    "        'shadowBlur':1,\n",
    "        'areaColor':'#2b3441'\n",
    "    }\n",
    "}\n",
    "select_country = [\n",
    "    'India', 'China', 'Turkey', 'Cuba', 'Russia', 'New Zealand', 'France',\n",
    "    'United Kingdom', 'Iceland', 'Canada', 'Australia', 'United States', 'Norway'\n",
    "]\n",
    "\n",
    "t3 = Timeline(init_opts=opts.InieOpts(theme=ThemeType.CHALK,width='100%',height='100vh'))\n",
    "count=0\n",
    "for index,year in enumerate(years):\n",
    "    geo = (\n",
    "        Geo(is_ignore_nonexistent_crood=True)\n",
    "        .add_schema(maptype='world',zoom=1,itemstyle_opts=itemstyle_geo)\n",
    "        .add(\"\",data_pair=[i for i in data_bar[year] if i[0] in select_country],\n",
    "            type_=ChartType.EFFECT_SCATTER)\n",
    "        .set_series_opts(label_opts=opts.LabelOpts(\n",
    "            is_show=True,\n",
    "            position='right',\n",
    "            color='white',\n",
    "            font_size=16,\n",
    "            font_weight='bold',\n",
    "            formatter=JsCode(\"function(x) {console.log(x); return x.name + ':' + x.value[2];}\")\n",
    "        ))\n",
    "    )\n",
    "    t3.add(geo,year)\n",
    "\n",
    "t3.add_schema(play_interval=400)\n",
    "t3.render('动态时序-地图.html')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
